<template>
  <div class="image-message" :class="{ 'own-message': isOwn }">
    <!-- 消息头部信息 -->
    <div v-if="!isOwn" class="message-header">
      <el-avatar
        :size="32"
        :src="message.senderAvatar"
        :alt="message.senderName"
      >
        {{ message.senderName?.charAt(0) }}
      </el-avatar>
      <div class="sender-info">
        <span class="sender-name">{{ message.senderName }}</span>
        <span class="message-time">{{ formatTime(message.timestamp) }}</span>
      </div>
    </div>

    <!-- 消息内容 -->
    <div class="message-content">
      <div class="message-bubble" :class="{ 'own-bubble': isOwn }">
        <!-- 图片预览 -->
        <div class="image-container">
          <el-image
            :src="imageUrl"
            :alt="message.fileName || '图片'"
            fit="cover"
            class="message-image"
            :preview-src-list="imageUrl ? [imageUrl] : []"
            :initial-index="0"
            preview-teleported
            :loading="imageLoading"
          >
            <template #placeholder>
              <div class="image-placeholder">
                <el-icon class="loading-icon"><Loading /></el-icon>
                <span>{{ imageLoading ? '认证加载中...' : '加载中...' }}</span>
              </div>
            </template>
            <template #error>
              <div class="image-error">
                <el-icon class="error-icon"><Picture /></el-icon>
                <span>{{ imageError ? '认证失败或图片损坏' : '图片加载失败' }}</span>
                <el-button
                  size="small"
                  text
                  @click="loadImageWithAuth"
                  style="margin-top: 4px;"
                >
                  重新加载
                </el-button>
              </div>
            </template>
          </el-image>
          
          <!-- 图片信息 -->
          <div v-if="message.fileName" class="image-info">
            <span class="file-name">{{ message.fileName }}</span>
            <span v-if="message.fileSize" class="file-size">
              {{ formatFileSize(message.fileSize) }}
            </span>
          </div>
        </div>
        
        <!-- 消息状态（仅自己的消息显示） -->
        <div v-if="isOwn" class="message-status">
          <el-icon v-if="message.messageStatus === 'sending'" class="status-sending">
            <Loading />
          </el-icon>
          <el-icon v-else-if="message.messageStatus === 'sent'" class="status-sent">
            <Check />
          </el-icon>
          <el-icon v-else-if="message.messageStatus === 'failed'" class="status-failed">
            <Close />
          </el-icon>
          <span class="message-time">{{ formatTime(message.timestamp) }}</span>
        </div>

        <!-- 加密状态指示器 -->
        <div v-if="message.isEncrypted" class="encryption-status">
          <el-tooltip content="此图片已加密" placement="top">
            <el-icon class="encryption-icon">
              <Lock />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 消息操作菜单 -->
    <div class="message-actions" v-show="showActions">
      <el-button-group size="small">
        <el-button :icon="ChatLineRound" @click="replyMessage" title="回复">
        </el-button>
        <el-button :icon="Download" @click="downloadImage" title="下载">
        </el-button>
        <el-button 
          v-if="isOwn" 
          :icon="Delete" 
          @click="deleteMessage" 
          title="删除"
          type="danger"
        >
        </el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {
  Loading,
  Check,
  Close,
  Picture,
  ChatLineRound,
  Download,
  Delete,
  Lock
} from '@element-plus/icons-vue'

// 类型定义
interface TeamMessage {
  id: number | string
  teamId: number
  senderId: number
  senderName: string
  senderAvatar?: string
  messageType: 'text' | 'image' | 'file'
  content: string
  fileName?: string
  fileSize?: number
  fileUrl?: string
  messageStatus: 'sending' | 'queued' | 'sent' | 'delivered' | 'failed'
  timestamp: number
  // 加密相关字段
  iv?: string
  encryptionAlgorithm?: string
  keyVersion?: number
  isEncrypted?: boolean
}

// Props
interface Props {
  message: TeamMessage
  isOwn: boolean
}

const props = defineProps<Props>()

// 响应式数据
const showActions = ref(false)
const imageUrl = ref<string>('')
const imageLoading = ref(true)
const imageError = ref(false)

// 调试信息
console.log('🖼️ ImageMessage组件接收到的消息数据:', props.message)

// 带认证的图片加载方法
const loadImageWithAuth = async () => {
  try {
    imageLoading.value = true
    imageError.value = false

    const fileUrl = props.message.fileUrl || props.message.content
    if (!fileUrl) {
      console.warn('⚠️ 图片URL为空:', props.message)
      imageError.value = true
      return
    }

    // 统一URL格式处理
    let correctedUrl = normalizeFileUrl(fileUrl)
    console.log('🖼️ 加载图片URL:', correctedUrl)

    // 使用axios发起带认证的请求
    const response = await axios.get(correctedUrl, {
      responseType: 'blob',
      timeout: 30000 // 30秒超时
    })

    // 创建blob URL
    const blob = new Blob([response.data], { type: response.headers['content-type'] || 'image/*' })
    const blobUrl = URL.createObjectURL(blob)

    imageUrl.value = blobUrl
    console.log('✅ 图片加载成功:', correctedUrl)

  } catch (error) {
    console.error('❌ 图片加载失败:', error)
    imageError.value = true
    ElMessage.error('图片加载失败')
  } finally {
    imageLoading.value = false
  }
}

// 组件挂载时加载图片
onMounted(() => {
  loadImageWithAuth()
})

// 组件卸载时清理blob URL
onUnmounted(() => {
  if (imageUrl.value && imageUrl.value.startsWith('blob:')) {
    URL.revokeObjectURL(imageUrl.value)
  }
})

// 方法
const getImageUrl = () => {
  const fileUrl = props.message.fileUrl || props.message.content
  if (!fileUrl) {
    console.warn('⚠️ 图片URL为空:', props.message)
    return ''
  }

  // 如果URL已经是完整的HTTP URL，直接返回
  if (fileUrl.startsWith('http')) {
    return fileUrl
  }

  // 统一URL格式处理
  let correctedUrl = normalizeFileUrl(fileUrl)

  console.log('🖼️ 原始URL:', fileUrl)
  console.log('🖼️ 修正后URL:', correctedUrl)
  return correctedUrl
}

// 统一的文件URL格式化函数
const normalizeFileUrl = (url: string): string => {
  // 如果是旧格式 /api/files/download/{id}，转换为新格式 /api/files/{id}/download
  if (url.match(/^\/api\/files\/download\/\d+$/)) {
    const fileId = url.split('/').pop()
    return `/api/files/${fileId}/download`
  }

  // 如果是文件路径格式 /api/files/download/{path}，提取文件ID
  if (url.match(/^\/api\/files\/download\/.+/)) {
    // 这种情况下，我们需要从消息中获取文件ID
    // 因为路径格式不包含文件ID
    console.warn('⚠️ 检测到文件路径格式URL，尝试从消息ID构建:', url)
    return `/api/files/${props.message.id}/download`
  }

  // 如果不是以/api开头，添加/api前缀
  if (!url.startsWith('/api')) {
    return `/api${url}`
  }

  return url
}
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 小于1分钟显示"刚刚"
  if (diff < 60000) {
    return '刚刚'
  }
  
  // 小于1小时显示分钟
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  
  // 小于24小时显示小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  
  // 今天显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })}`
  }
  
  // 其他显示日期时间
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const replyMessage = () => {
  // TODO: 实现回复功能
  ElMessage.info('回复功能开发中...')
}

const downloadImage = async () => {
  try {
    const imageUrl = props.message.fileUrl || props.message.content
    const fileName = props.message.fileName || `image_${props.message.id}.jpg`
    
    // 创建下载链接
    const link = document.createElement('a')
    link.href = imageUrl
    link.download = fileName
    link.target = '_blank'
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('图片下载开始')
  } catch (error) {
    ElMessage.error('图片下载失败')
  }
}

const deleteMessage = () => {
  // TODO: 实现删除功能
  ElMessage.info('删除功能开发中...')
}
</script>

<style scoped lang="scss">
.image-message {
  position: relative;
  margin-bottom: 16px;
  
  &:hover .message-actions {
    opacity: 1;
  }

  &.own-message {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
  }
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;

  .sender-info {
    display: flex;
    flex-direction: column;
    gap: 2px;

    .sender-name {
      font-size: 14px;
      font-weight: 600;
      color: var(--el-color-primary);
    }

    .message-time {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}

.message-content {
  position: relative;
  max-width: 400px;
  
  .own-message & {
    max-width: 400px;
  }
}

.message-bubble {
  position: relative;
  padding: 8px;
  border-radius: 12px;
  background: var(--el-bg-color-page);
  border: 1px solid var(--el-border-color-lighter);

  &.own-bubble {
    background: var(--el-bg-color-page);
    border-color: var(--el-color-primary);
  }

  // 消息气泡箭头
  &::before {
    content: '';
    position: absolute;
    top: 12px;
    left: -8px;
    width: 0;
    height: 0;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
    border-right: 8px solid var(--el-bg-color-page);
  }

  &.own-bubble::before {
    left: auto;
    right: -8px;
    border-right: none;
    border-left: 8px solid var(--el-bg-color-page);
    border-left-color: var(--el-bg-color-page);
  }
}

.image-container {
  .message-image {
    width: 100%;
    max-width: 300px;
    max-height: 200px;
    border-radius: 8px;
    cursor: pointer;
    transition: transform 0.2s;

    &:hover {
      transform: scale(1.02);
    }
  }

  .image-placeholder,
  .image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 120px;
    background: var(--el-fill-color-light);
    border-radius: 8px;
    color: var(--el-text-color-secondary);
    font-size: 14px;

    .loading-icon,
    .error-icon {
      font-size: 24px;
      margin-bottom: 8px;
    }

    .loading-icon {
      animation: spin 1s linear infinite;
    }
  }

  .image-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8px;
    padding: 4px 8px;
    background: var(--el-fill-color-lighter);
    border-radius: 6px;
    font-size: 12px;

    .file-name {
      color: var(--el-text-color-primary);
      font-weight: 500;
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .file-size {
      color: var(--el-text-color-secondary);
      margin-left: 8px;
    }
  }
}

.message-status {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);

  .status-sending {
    animation: spin 1s linear infinite;
    color: var(--el-color-primary);
  }

  .status-sent {
    color: var(--el-color-success);
  }

  .status-failed {
    color: var(--el-color-error);
  }

  .message-time {
    color: var(--el-text-color-secondary);
  }
}

.encryption-status {
  display: flex;
  align-items: center;
  margin-top: 8px;

  .encryption-icon {
    font-size: 12px;
    color: var(--el-color-success);
    opacity: 0.7;
    transition: opacity 0.2s;

    &:hover {
      opacity: 1;
    }
  }
}

.message-actions {
  position: absolute;
  top: -8px;
  right: 16px;
  opacity: 0;
  transition: opacity 0.2s;
  background: var(--el-bg-color);
  border-radius: 6px;
  box-shadow: var(--el-box-shadow-light);
  z-index: 10;

  .own-message & {
    right: auto;
    left: 16px;
  }

  .el-button-group {
    .el-button {
      border-radius: 4px;
      padding: 4px 8px;
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .message-content {
    max-width: 280px;
  }

  .image-container .message-image {
    max-width: 250px;
    max-height: 180px;
  }

  .message-actions {
    position: static;
    opacity: 1;
    margin-top: 8px;
    background: transparent;
    box-shadow: none;
  }
}
</style>
